package org.springblade.modules.alimqtt.config;

import com.alibaba.mqtt.server.ServerConsumer;
import com.alibaba.mqtt.server.ServerProducer;
import com.alibaba.mqtt.server.config.ChannelConfig;
import com.alibaba.mqtt.server.config.ConsumerConfig;
import com.alibaba.mqtt.server.config.ProducerConfig;
import org.jetbrains.annotations.NotNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//import org.springframework.integration.config.EnableIntegration;

import javax.annotation.Resource;

@Configuration
//@EnableIntegration
@ConditionalOnProperty(name ="aliyun.mqtt.enable", havingValue = "true",matchIfMissing = false)
public class AliyunMqttClientConfig {
    @Resource
    private AliyunMqttProperties aliyunMqttProperties;

    @Bean
    public ServerProducer serverProducer() throws Exception {
        ChannelConfig channelConfig = getChannelConfig();
        ServerProducer serverProducer = new ServerProducer(channelConfig, new ProducerConfig());
        serverProducer.start();
        return serverProducer;
    }

    @NotNull
    private ChannelConfig getChannelConfig() {
        ChannelConfig channelConfig = new ChannelConfig();
        channelConfig.setDomain(aliyunMqttProperties.getDomain());
        channelConfig.setPort(aliyunMqttProperties.getPort());
        channelConfig.setInstanceId(aliyunMqttProperties.getInstance());
        channelConfig.setAccessKey(aliyunMqttProperties.getAccessKey());
        channelConfig.setSecretKey(aliyunMqttProperties.getSecretKey());
        return channelConfig;
    }

    @Bean
    public ServerConsumer serverConsumer() throws Exception {
        ServerConsumer serverConsumer = new ServerConsumer(getChannelConfig(), new ConsumerConfig());
        serverConsumer.start();
        return serverConsumer;
    }

}
